/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package gamecaroonline;

import java.io.*;
import java.net.*;
import java.util.*;
import java.text.SimpleDateFormat;

/**
 *
 * @author Loren_kn92
 */
public class Server {
    // a unique ID for each connection
    private static int uniqueId;
    // an ArrayList to keep the list of the Client
    private ArrayList<ClientThread> clients;
    // if I am in a GUI
    private ServerJFrame sg;
    // to display time
    private SimpleDateFormat sdf;
    // the port number to listen for connection
    private int port;
    // the boolean that will be turned of to stop the server
    private boolean keepGoing;
    
    /**
     * server constructor that receive the port to 
     * listen to for connection as parameter
     * in console
     */

    public Server(int port){
        this(port, null);
    }
    
    public Server(ServerJFrame sg){
        this(Integer.parseInt(sg.jTextField2.getText()),sg);
    }
    
    public Server(int port, ServerJFrame sg){
        // GUI or not
        this.sg = sg;
        // the port
        this.port = port;
        // to display hh:mm:ss
        this.sdf = new SimpleDateFormat("HH:mm:ss");
        this.clients = new ArrayList<ClientThread>();
        
        if(this.sg!=null){
            
        }
    }
    
    public void start(){
        this.keepGoing = true;
        // Create socket server and wait for connection request
        try{
            DatagramSocket serverSocket = new DatagramSocket(this.port);
            byte[] receiveData = new byte[1024];             
            byte[] sendData = new byte[1024];
            // infinite loop to wait for connection
            while(this.keepGoing){
                writeLog("Server waiting for clients on port " + port + ".");
                DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
                serverSocket.receive(receivePacket);
                if(!keepGoing){
                    break;
                }
            }
        }catch(Exception e){
            System.err.println("Error: "+e.getMessage());
            if(sg!=null){
                this.writeLog("Error: "+e.getMessage());
            }
        }
    }
    
    public void stop(){
        keepGoing = false;
        writeLog("Server stoped.");
    }
    
    public void writeLog(String msg){
        String event = sdf.format(new Date())+ " " + msg;
        if(sg==null){
            System.err.println(event);
        }else{
            sg.writeLog(event);
        }
    }
    
    public int getPort(){
        return port;
    }
    
    public boolean isRuning(){
        return keepGoing;
    }
    
    class ClientThread extends Thread{
    
    }
}

